<?php
declare(strict_types=1);

namespace ServerApp\lib\server\http;

use ServerApp\lib\connection\ConfClient;
use ServerApp\lib\core\ServerType;
use ServerApp\lib\process\SProcess;
use ServerApp\lib\memory\Chan;
use ServerApp\lib\util\ServerHelper;
use stdClass;

/**
 *
 */
class HttpPush
{
    private $pushTask = [];
    private $pushTaskNum = 2;

    private function createPushTask(){
        $worker_index = count($this->pushTask);
        $taskProcess = new SProcess(function() use($worker_index){
            ConfClient::init(ServerType::HTTP, $worker_index);
            ConfClient::getInstance()->run();
//            swoole_event_add(SGlobal::$process->pipe, [SGlobal::$conf_client, 'die']);
            $tmp = new stdClass();
            $tmp->func = function() use ($tmp) {
                while ($data = Chan::getInstance()->pop()) {
                    $this->func->task($data);
                }
                swoole_timer_after(1000, $tmp->func);
            };
            ($tmp->func)();
        }, false, 2, "task_$worker_index");
        $pid = $taskProcess->start();
        $this->pushTask[$pid] = [$worker_index, $taskProcess];
    }

    private function writePid(){
        $content = implode('|', array_keys($this->pushTask));
        $s = explode('\\', __CLASS__);
        file_put_contents(ServerHelper::getInstance()->getPidPath() . end($s) . __LINE__ . ".pid", $content);
    }

    private $func;

    /**
     * AndroidPush constructor.
     * @param IHttp $func2
     */
    private function __construct(IHttp $func2){
        $this->func = $func2;
        for ($i = 0; $i < $this->pushTaskNum; $i++) {
            $this->createPushTask();
        }

        $this->writePid();

        SProcess::signal(SIGCHLD, function ($sig) {
            echo "sig:$sig\n";
            for(;;){
                $ret = SProcess::wait();
                if ($ret) {
                    $pid = $ret['pid'];
                    if (isset($this->pushTask[$pid])){
                        unset($this->pushTask[$pid]);
                        $this->createPushTask();
                    }
                } else {
                    $this->writePid();
                }
            }
        });
    }

    private static $instance = null;


    /**
     * @param IHttp $func2
     */
    public static function init(IHttp $func2) {
        if (self::$instance === null) {
            self::$instance = new self($func2);
        }
    }
}